import React from 'react';
import { Card, Button, Space, Input, Select, Table, Modal, Form, Tabs, message } from 'antd';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  ApiOutlined,
  DatabaseOutlined,
  CodeOutlined,
  EyeOutlined
} from '@ant-design/icons';

const { TextArea } = Input;
const { Option } = Select;

export default function DataSourcePanel() {
  const [dataSources, setDataSources] = React.useState([
    {
      id: '1',
      name: '用户列表',
      type: 'api',
      url: '/api/users',
      method: 'GET',
      description: '获取用户列表数据'
    },
    {
      id: '2',
      name: '产品数据',
      type: 'static',
      data: JSON.stringify([
        { id: 1, name: '产品A', price: 100 },
        { id: 2, name: '产品B', price: 200 }
      ], null, 2),
      description: '静态产品数据'
    }
  ]);
  
  const [modalVisible, setModalVisible] = React.useState(false);
  const [editingSource, setEditingSource] = React.useState(null);
  const [form] = Form.useForm();

  // 数据源类型配置
  const dataSourceTypes = [
    { value: 'api', label: 'API接口', icon: <ApiOutlined /> },
    { value: 'static', label: '静态数据', icon: <DatabaseOutlined /> },
    { value: 'variable', label: '变量', icon: <CodeOutlined /> }
  ];

  // 表格列配置
  const columns = [
    {
      title: '数据源名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => (
        <Space>
          {dataSourceTypes.find(t => t.value === record.type)?.icon}
          {text}
        </Space>
      )
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (type) => dataSourceTypes.find(t => t.value === type)?.label
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="text" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => handlePreview(record)}
          />
          <Button 
            type="text" 
            size="small" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Button 
            type="text" 
            size="small" 
            icon={<DeleteOutlined />}
            danger
            onClick={() => handleDelete(record.id)}
          />
        </Space>
      )
    }
  ];

  // 添加数据源
  const handleAdd = () => {
    setEditingSource(null);
    form.resetFields();
    setModalVisible(true);
  };

  // 编辑数据源
  const handleEdit = (source) => {
    setEditingSource(source);
    form.setFieldsValue(source);
    setModalVisible(true);
  };

  // 删除数据源
  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个数据源吗？',
      onOk: () => {
        setDataSources(dataSources.filter(ds => ds.id !== id));
        message.success('数据源已删除');
      }
    });
  };

  // 预览数据源
  const handlePreview = (source) => {
    Modal.info({
      title: `预览数据源: ${source.name}`,
      width: 600,
      content: (
        <div>
          <p><strong>类型:</strong> {dataSourceTypes.find(t => t.value === source.type)?.label}</p>
          <p><strong>描述:</strong> {source.description}</p>
          {source.type === 'api' && (
            <>
              <p><strong>URL:</strong> {source.url}</p>
              <p><strong>方法:</strong> {source.method}</p>
            </>
          )}
          {source.type === 'static' && (
            <>
              <p><strong>数据:</strong></p>
              <pre style={{ 
                background: '#f5f5f5', 
                padding: 8, 
                borderRadius: 4,
                maxHeight: 200,
                overflow: 'auto'
              }}>
                {source.data}
              </pre>
            </>
          )}
        </div>
      )
    });
  };

  // 保存数据源
  const handleSave = async () => {
    try {
      const values = await form.validateFields();
      
      if (editingSource) {
        // 编辑模式
        setDataSources(dataSources.map(ds => 
          ds.id === editingSource.id ? { ...ds, ...values } : ds
        ));
        message.success('数据源已更新');
      } else {
        // 新增模式
        const newSource = {
          id: Date.now().toString(),
          ...values
        };
        setDataSources([...dataSources, newSource]);
        message.success('数据源已添加');
      }
      
      setModalVisible(false);
      form.resetFields();
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  // 根据数据源类型渲染不同的表单字段
  const renderFormFields = () => {
    const type = form.getFieldValue('type');
    
    switch (type) {
      case 'api':
        return (
          <>
            <Form.Item 
              label="API地址" 
              name="url" 
              rules={[{ required: true, message: '请输入API地址' }]}
            >
              <Input placeholder="例如: /api/users" />
            </Form.Item>
            <Form.Item 
              label="请求方法" 
              name="method" 
              rules={[{ required: true, message: '请选择请求方法' }]}
            >
              <Select>
                <Option value="GET">GET</Option>
                <Option value="POST">POST</Option>
                <Option value="PUT">PUT</Option>
                <Option value="DELETE">DELETE</Option>
              </Select>
            </Form.Item>
            <Form.Item label="请求头" name="headers">
              <TextArea 
                rows={3} 
                placeholder="请输入JSON格式的请求头，例如: {&quot;Content-Type&quot;: &quot;application/json&quot;}"
              />
            </Form.Item>
            <Form.Item label="请求参数" name="params">
              <TextArea 
                rows={3} 
                placeholder="请输入JSON格式的请求参数"
              />
            </Form.Item>
          </>
        );
      
      case 'static':
        return (
          <Form.Item 
            label="静态数据" 
            name="data" 
            rules={[{ required: true, message: '请输入静态数据' }]}
          >
            <TextArea 
              rows={8} 
              placeholder="请输入JSON格式的静态数据"
            />
          </Form.Item>
        );
      
      case 'variable':
        return (
          <>
            <Form.Item 
              label="变量名" 
              name="variableName" 
              rules={[{ required: true, message: '请输入变量名' }]}
            >
              <Input placeholder="例如: userInfo" />
            </Form.Item>
            <Form.Item 
              label="默认值" 
              name="defaultValue"
            >
              <TextArea 
                rows={3} 
                placeholder="请输入变量的默认值"
              />
            </Form.Item>
          </>
        );
      
      default:
        return null;
    }
  };

  return (
    <div style={{ padding: 16, height: 'calc(100vh - 200px)', overflowY: 'auto' }}>
      <Card 
        size="small" 
        title="数据源管理"
        extra={
          <Button 
            type="primary" 
            size="small" 
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加数据源
          </Button>
        }
        style={{ marginBottom: 16 }}
      >
        <Table
          columns={columns}
          dataSource={dataSources}
          rowKey="id"
          size="small"
          pagination={false}
        />
      </Card>

      {/* 数据源统计 */}
      <Card size="small" title="数据源统计">
        <div style={{ fontSize: 12, color: '#666' }}>
          <div>总数据源: {dataSources.length}</div>
          <div>API接口: {dataSources.filter(ds => ds.type === 'api').length}</div>
          <div>静态数据: {dataSources.filter(ds => ds.type === 'static').length}</div>
          <div>变量: {dataSources.filter(ds => ds.type === 'variable').length}</div>
        </div>
      </Card>

      {/* 添加/编辑数据源弹窗 */}
      <Modal
        title={editingSource ? '编辑数据源' : '添加数据源'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        width={600}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ type: 'api', method: 'GET' }}
        >
          <Form.Item 
            label="数据源名称" 
            name="name" 
            rules={[{ required: true, message: '请输入数据源名称' }]}
          >
            <Input placeholder="请输入数据源名称" />
          </Form.Item>
          
          <Form.Item 
            label="数据源类型" 
            name="type" 
            rules={[{ required: true, message: '请选择数据源类型' }]}
          >
            <Select onChange={() => form.resetFields(['url', 'method', 'headers', 'params', 'data', 'variableName', 'defaultValue'])}>
              {dataSourceTypes.map(type => (
                <Option key={type.value} value={type.value}>
                  <Space>
                    {type.icon}
                    {type.label}
                  </Space>
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item 
            label="描述" 
            name="description"
          >
            <TextArea rows={2} placeholder="请输入数据源描述" />
          </Form.Item>
          
          {renderFormFields()}
        </Form>
      </Modal>
    </div>
  );
} 